package com.xunshibao.spring.validator;

import java.io.IOException;
import java.io.InputStream;

import org.apache.commons.validator.Validator;
import org.apache.commons.validator.ValidatorResources;
import org.springframework.beans.FatalBeanException;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.core.io.Resource;
import org.springframework.validation.Errors;
import org.springmodules.validation.commons.DefaultValidatorFactory;
import org.xml.sax.SAXException;

public class SpringExtValidatorFactory implements InitializingBean {
	private ValidatorResources validatorResources;

	public void setValidationConfigLocations(Resource[] validationConfigLocations) {
		try {
            InputStream[] inputStreams = new InputStream[validationConfigLocations.length];

            for (int i = 0; i < inputStreams.length; i++) {
                inputStreams[i] = validationConfigLocations[i].getInputStream();
            }

            this.validatorResources = new ValidatorResources(inputStreams);
        }
        catch (IOException e) {
            throw new FatalBeanException("Unable to read validation configuration due to IOException.", e);
        }
        catch (SAXException e) {
            throw new FatalBeanException("Unable to parse validation configuration XML", e);
        }
	}
	
	public void afterPropertiesSet() throws Exception {
        if (this.validatorResources == null) {
            throw new FatalBeanException("Unable to locate validation configuration. Property [validationLocations] is required.");
        }
    }
	
	public Validator getValidator(String beanName, Object bean, Errors errors) {
        Validator validator = new Validator(validatorResources, beanName);
        validator.setParameter(DefaultValidatorFactory.ERRORS_KEY, errors);
        validator.setParameter(Validator.BEAN_PARAM, bean);
        return validator;
    }
}
